<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <title>JS判断URL是否可访问</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <div>检验的url地址：</div>
    <input type="text" id="urlText" value="https://www.baidu.com/" />
    <input type="button" value="判断是否可访问" onclick="getURL()" />
    <br />
    <div id="msg1"></div>
    <div id="msg"></div>

    <script>
      function getURL() {
        $("#msg").html("");
        var url = $("#urlText").val();
        var dateTime = disptime();
        var time2 = dateTime.DateTime;
        $("#msg1").html("发送时间：" + time2);

        // JSONP 请求
        $.ajax({
          type: "GET",
          url: url,
          cache: false,
          dataType: "jsonp", // 指定为JSONP类型
          timeout: 10000, // 设置超时时间
          success: function (data) {
            var dateTime2 = disptime();
            var time22 = dateTime2.DateTime;
            var htmlTxt = [];
            if (data && typeof data === "object") {
              // 判断是否成功获取数据
              htmlTxt.push("成功<br/>");
            } else {
              htmlTxt.push("失败<br/>");
            }
            htmlTxt.push(
              "readyState=" +
                this.readyState +
                "<br/>" +
                "status=" +
                this.status +
                "<br/>" +
                "statusText=" +
                this.statusText +
                "<br/>" +
                "响应时间：" +
                time22
            );
            var htmlString = htmlTxt.join("");
            $("#msg").html(htmlString);
          },
          error: function (jqXHR, textStatus, errorThrown) {
            var htmlTxt = ["请求失败<br/>"];
            htmlTxt.push(
              "readyState=" +
                jqXHR.readyState +
                "<br/>" +
                "status=" +
                jqXHR.status +
                "<br/>" +
                "statusText=" +
                jqXHR.statusText
            );
            var htmlString = htmlTxt.join("");
            $("#msg").html(htmlString);
          },
        });
      }

      function disptime() {
        var date = new Date();
        var yyyy = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var HH = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        return {
          DateTime:
            yyyy +
            "-" +
            (month < 10 ? "0" : "") +
            month +
            "-" +
            (day < 10 ? "0" : "") +
            day +
            " " +
            (HH < 10 ? "0" : "") +
            HH +
            ":" +
            (minute < 10 ? "0" : "") +
            minute +
            ":" +
            (second < 10 ? "0" : "") +
            second,
        };
      }
    </script>
  </body>
</html>
